package handler

import (
	"net/http"

	"database/sql"

	"gitee.com/hp-huiw/family-expense-api/internal/service"
	"github.com/gin-gonic/gin"
)

type UserActiveTokenHandler interface {
	QueryDeviceByUsername(ctx *gin.Context)
	UpdateEnabled(ctx *gin.Context)
	Delete(ctx *gin.Context)
}

func NewUserActiveTokenHandler(db *sql.DB) UserActiveTokenHandler {
	return &userActiveTokenHandler{
		userActiveTokenService: service.NewUserActiveTokenService(db),
	}
}

// Matches /query-device-by-username of http get action.
func (h *userActiveTokenHandler) QueryDeviceByUsername(ctx *gin.Context) {
	c := ctx.Request.Context()
	username := GetClaims(ctx).Username
	result, err := h.userActiveTokenService.QueryDevice(c, username)

	if err != nil {
		ctx.Error(err)
		return
	}

	SendDataResponse(ctx, result)
}

// Matches /update-enabled of http post action.
func (h *userActiveTokenHandler) UpdateEnabled(ctx *gin.Context) {
	var postedData struct {
		ID      string `json:"id"`
		Enabled bool   `json:"enabled"`
	}

	if err := ctx.ShouldBindJSON(&postedData); err != nil {
		ctx.Error(err)
		return
	}

	c := ctx.Request.Context()
	username := GetClaims(ctx).Username
	err := h.userActiveTokenService.UpdateEnabled(c, postedData.ID, username, postedData.Enabled)

	if err != nil {
		ctx.Error(err)
		return
	}

	SendStatusResponse(ctx, http.StatusNoContent)
}

// Matches /delete of http post action.
func (h *userActiveTokenHandler) Delete(ctx *gin.Context) {
	var postedData struct {
		ID string `json:"id"`
	}

	if err := ctx.ShouldBindJSON(&postedData); err != nil {
		ctx.Error(err)
		return
	}

	c := ctx.Request.Context()
	claims := GetClaims(ctx)
	username := claims.Username
	err := h.userActiveTokenService.DeleteByIDAndUsername(c, postedData.ID, username)

	if err != nil {
		ctx.Error(err)
		return
	}

	SendStatusResponse(ctx, http.StatusNoContent)
}

// Container of UserActiveTokenHandler functions.
type userActiveTokenHandler struct {
	userActiveTokenService service.UserActiveTokenService
}
